<?php

namespace App\Services\Pay;


use App\Dao\OrderDao;
use App\Exception\MessageException;
use App\Model\Order;
use App\Services\Pay\Google\GooglePay;
use App\Services\PayPlus\IndoPlusPayment;
use App\Utils\LoggerUtil;
use App\Utils\RedisClient;
use App\Utils\ToolUtil;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class RechargeService
{

    /**
     * Note - 验证apple内购订单
     * DateTime 2024/8/26 10:51
     * User Admin
     * @param $params
     */
    public function appleOrder($params)
    {
        LoggerUtil::write("apple_check_order", $params, 'apple_pay_params');

        $out_trade_no = $params['out_trade_no'] ?? '';// 订单id
        $encodeStr = $params['encodeStr'] ?? ""; // 苹果支付回调参数
        // 苹果支付单号
        $transaction_id = $params['transaction_id'] ?: '';

        // $orderModel = new OrderModel();
        // $orderInfo = $orderModel->findOrderByOrderId($order_id);
        $orderInfo = OrderDao::getInstance()->findOrderByOrderId($out_trade_no);
        if (empty($orderInfo) || $orderInfo['notify_status'] != 0) {
            // Tool::JSON(\CodeData::NEED_TIPS, [], "订单信息错误！");
            throw new MessageException("订单信息错误！");
        }

        $url = "https://buy.itunes.apple.com/verifyReceipt";
        $post_json = json_encode(array('receipt-data' => $encodeStr));
        // $result = do_http_post($url, $post_json);
        $result = ToolUtil::api_curl($url, $post_json, [], 5);
        $result = json_decode($result, true);

        if ($result['status'] == '21007') {
            // 沙箱测试环境
            $url = "https://sandbox.itunes.apple.com/verifyReceipt";
            $result = ToolUtil::api_curl($url, $post_json, [], 5);
            $result = json_decode($result, true);
        }
        LoggerUtil::write("apple_check_order", $result, 'apple_pay_result');
        if ($result['status'] == 0) {
            if (count($result['receipt']['in_app'])) {
                $inApp = $result['receipt']['in_app'];
                foreach ($inApp as $value) {
                    if ($value['transaction_id'] == $transaction_id) {
                        $trade_id = $value['original_transaction_id'];
                        break;
                    }
                }
                if (!isset($trade_id)) {
                    throw new MessageException("未查询到支付订单信息！");
                }
                // include(ROOT_PATH . "app/v1/pay/pay_callback_common.php");
                (new PayCallbackCommon())->do($out_trade_no, $trade_id);
                // Tool::JSON(\CodeData::SUCCESS, ['result' => 1, 'msg' => array()], "订单支付完成！");
            }
        } else {
            // Tool::JSON(\CodeData::NEED_TIPS, [], "未查询到支付订单信息！");
            throw new MessageException("未查询到支付订单信息！");
        }

    }


    /**
     * Note - 验证google内购订单
     * DateTime 2024/8/23 16:03
     * User Admin
     * @param $params
     * @return array
     */
    public function googleOrder($params)
    {
        LoggerUtil::write("google_check_order", $params, 'params');

        $out_trade_no = $params['out_trade_no']; // 平台预生成订单号
        $pid = $params['productId'];
        $orderToken = $params['purchaseToken'];
        $packageName = $params['package'];
        $googleOrderId = $params['googleOrderId'];


        // 通过订单信息获取支付参数
        $orderInfo = OrderDao::getInstance()->findOrderByOrderId($out_trade_no);
        if ($orderInfo['notify_status'] == 1 && $orderInfo['pay_status'] == 1) {
            // Tool::JSON(\CodeData::NEED_TIPS, [],'订单已处理');
            throw new MessageException('订单已处理');
        }

        $google = new GooglePay();
        $contents = $google->verifyOrder($pid, $orderToken, $packageName);
        LoggerUtil::write("google_check_order", $contents, 'google_pay_result');

        if ($contents['purchaseState'] === 1) {
            // 订单已取消
            LoggerUtil::write("google_check_order", $out_trade_no . ',订单已取消');
            throw new MessageException('订单已取消');
        }
        if ($contents['purchaseState'] === 2) {
            // 订单已取消
            LoggerUtil::write("google_check_order", $out_trade_no . ',订单等待中');
            throw new MessageException('订单等待中');
        }

        if ($contents['orderId'] != $googleOrderId) {
            LoggerUtil::write("google_check_order", $out_trade_no . '!=' . $contents['orderId'] . ',订单号不一致');
            throw new MessageException('订单号不一致');
        }

        $trade_id = $contents['orderId']; // GooglePay支付订单号
        $tradeIdExist = Order::query()->where('trade_id', $trade_id)->exists();
        if ($tradeIdExist) {
            LoggerUtil::write("google_check_order", $out_trade_no . ',已经被消耗');
            throw new MessageException('已经被消耗');
        }
        LoggerUtil::write("google_check_order", $out_trade_no . ',消耗订单');
        // include(ROOT_PATH . "app/v1/pay/pay_callback_common.php");
        (new PayCallbackCommon())->do($out_trade_no, $trade_id);

    }


    /**
     * Note - 验证印度第三方订单
     * DateTime 2024/8/26 11:08
     * User Admin
     * @param $params
     */
    public function indoOrder($params)
    {
        LoggerUtil::write("indo_unsyn_callback", $params, 'params');
        if (empty($params['orderNo'])) {
            // Tool::log("indo_unsyn_callback", "回调参数错误！");
            LoggerUtil::write("indo_unsyn_callback", "回调参数错误！");
            // throw new MessageException("参数错误");
        }
        $redis = RedisClient::getInstance();
        if ($redis->get('indo_unsyn_callback_count_' . $params['orderNo']) >= 3) {
            // Tool::log("indo_unsyn_callback", "回调次数超过3次！");
            LoggerUtil::write("indo_unsyn_callback", "回调次数超过3次！");
            throw new MessageException("回调次数超过3次！");
        }
        $redis->incr('indo_unsyn_callback_count_' . $params['orderNo']);
        if (isset($params['status']) && $params['status'] != 2) {
            // Tool::log("indo_unsyn_callback.log", "支付状态错误！");
            LoggerUtil::write("indo_unsyn_callback", "支付状态错误！");
            // throw new MessageException("状态错误");
        }
        // $orderModel = new OrderModel();
        $orderInfo = OrderDao::getInstance()->findOrderByOrderId($params['orderNo']);
        $platform_id = $orderInfo['pay_platform_id'] ?: 0;
        $payment = new IndoPlusPayment($platform_id);
        $originData = $params;
        unset($originData['sign']);
        $sign = $payment->getSign($originData);
        if ($sign != $params['sign']) {
            // Tool::log("indo_unsyn_callback", "回调验签失败！");
            LoggerUtil::write("indo_unsyn_callback", "回调验签认证失败！");
            throw new MessageException("认证失败");
        }
        $order_id = $params['orderNo'];
        $trade_id = $orderInfo['trade_id'] ?? '';
        // include(ROOT_PATH . "app/v1/pay/pay_callback_common.php");
        (new PayCallbackCommon())->do($order_id, $trade_id);

    }
}